package com.example.autocode.controller;

import com.example.autocode.common.R;
import com.example.autocode.model.DataSource;
import com.example.autocode.model.Table;
import com.example.autocode.utils.DataSourceUtils;
import com.google.common.base.CaseFormat;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
public class DataSourceController {

    @PostMapping("/con")
    public R getConnection(@RequestBody DataSource dataSource) {
        try {
            if(!DataSourceUtils.init(dataSource)) {
                return R.error();
            }
        } catch (Exception e) {
            return R.error();
        }
        System.out.println(dataSource);
        Connection connection = DataSourceUtils.getConnection();
        List<Table> tableList = new ArrayList<>();
        try {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet tables = metaData.getTables(connection.getCatalog(), null, null, null);
            while(tables.next()) {
                String table_name = tables.getString("TABLE_NAME");
                String modelName = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, table_name);
                Table table = new Table();
                table.setTableName(table_name);
                table.setModelName(modelName);
                table.setMapperName(modelName + "Mapper");
                table.setServiceName(modelName + "Service");
                table.setServiceImplName(modelName + "ServiceImpl");
                table.setControllerName(modelName + "Controller");
                tableList.add(table);
            }
            return R.ok().data("tableList", tableList);
        } catch (SQLException e) {
            e.printStackTrace();
            return R.error();
        }
    }
}
